import router from "@/routers/index";
import { useUserStore, useAuthStore } from "@/stores/index";
import { AdminRoutes } from "./adminRouter";
import { userRoutes } from "./userRouter";

/**
 * @description 获取动态路由
 */
export const getDynamicRouters = () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();
  if (userStore.userInfo?.role) {
    if (userStore.userInfo?.role === 1) {
      const routers = [
        {
          name: "admin",
          path: "/admin",
          component: () => import("@/layouts/index.vue"),
          redirect: "/admin/user-manage",
          children: [...AdminRoutes],
          meta: {
            title: "框架"
          }
        }
      ];
      authStore.setAuthMenuList(AdminRoutes);
      return routers;
    } else if (userStore.userInfo?.role === 2) {
      const routers = [
        {
          name: "user",
          path: "/",
          component: () => import("@/layouts/index.vue"),
          redirect: "/case-all",
          children: [...userRoutes],
          meta: {
            title: "框架"
          }
        }
      ];
      authStore.setAuthMenuList(userRoutes);
      return routers;
    }
  }
  return [];
};

/**
 * @description 添加动态路由
 */
export const addDynamicRouter = async () => {
  const routers = getDynamicRouters();
  routers.forEach(r => {
    router.addRoute(r);
  });
};
